/**
 * Handler used to parse the wikiFacts response
 * 
 **/
package com.syde322;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.syde322.WikiFacts;


public class FactsHandler extends DefaultHandler {
    private StringBuffer buffer = new StringBuffer();
    
    private static ArrayList<WikiFacts> factsList;
    private WikiFacts fact;
    
    // using SAX parser to parse through WikiFacts XML nodes
    
    @Override
    public void startElement(String namespaceURI, String localName,
            String qName, Attributes atts) throws SAXException {
        
        buffer.setLength(0);
        
        if (localName.equals("Section")) {
            factsList = new ArrayList<WikiFacts>();
        }
        else if (localName.equals("Item")) {
            fact = new WikiFacts();
        }
    }

    // set the properties of the WikiFacts object
    public void endElement(String uri, String localName, String qName) throws SAXException {
        
        if (localName.equals("Item")) {
            factsList.add(fact);
        }
        else if (localName.equals("Text")) {
            fact.title = buffer.toString();
        }
        else if (localName.equals("Description")) {
            fact.description = buffer.toString();
        }
        else if (localName.equals("Url")) {
            fact.url = buffer.toString();
        }
    }
    
    public void characters(char[] ch, int start, int length) {
        buffer.append(ch, start, length);
    }
        
    public static ArrayList<WikiFacts> retrieveFactsList() {
        return factsList;
    }
}
